package com.nan.hrm.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.nan.hrm.LoginUserClient;
import com.nan.hrm.domain.Employee;
import com.nan.hrm.domain.LoginUser;
import com.nan.hrm.domain.Tenant;
import com.nan.hrm.domain.TenantMeal;
import com.nan.hrm.dto.TenantEnteringDto;
import com.nan.hrm.mapper.EmployeeMapper;
import com.nan.hrm.mapper.TenantMapper;
import com.nan.hrm.mapper.TenantMealMapper;
import com.nan.hrm.query.TenantQuery;
import com.nan.hrm.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.nan.hrm.util.AjaxResult;
import com.nan.hrm.util.PageList;
import com.nan.hrm.util.ValidUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author N
 * @since 2021-09-11
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TenantMealMapper tenantMealMapper;
    @Autowired
    private LoginUserClient loginUserClient;
    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        //分页条件，查询出来总数
        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());
        //跨表查询出来结构
        List<Tenant> datas =  tenantMapper.loadPageList(page,query);
        return new PageList<>(page.getTotal(),datas);
    }

    //租户入驻
    @Override
    public void entering(TenantEnteringDto tenantEnteringDto) {
        //拿到前端数据
        Tenant tenant = tenantEnteringDto.getTenant();
        Long mealId = tenantEnteringDto.getMealId();
        Employee employee = tenantEnteringDto.getEmployee();
        // 工具类数据校验
        ValidUtils.assertNotNull(tenant.getCompanyName(),"系统出错");
        ValidUtils.assertNotNull(employee.getTel(),"系统出错");
        //先保存auth中loginuser表
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(employee,loginUser);
        loginUser.setType(0);
        //拿出loginuser的id,等会保存到employee中
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        Long loginid = Long.valueOf(ajaxResult.getResultObj().toString());
        //再保存sysmanage中的employee表
        employee.setInputTime(new Date());
        employee.setState(0);
        employee.setType(5);
        employee.setLoginId(loginid);
        employeeMapper.insert(employee);
        //保存机构
        tenant.setRegisterTime(new Date());
        tenant.setState(0);
        tenant.setAdminId(employee.getId());
        tenantMapper.insert(tenant);
        //保存机构套餐
        TenantMeal tenantMeal = new TenantMeal();
        tenantMeal.setMealId(mealId);
        tenantMeal.setTenantId(tenant.getId());
        tenantMealMapper.insert(tenantMeal);
    }
}
